var mycode = null;
var mydatas = []; //用户选择的所有城市数组
var bingolen = 2;
// var arrlen = null;
$(document).ready(function() {
    reSuccess = false;
    success = false;
    login();
    // checkWin("0");
})

//获取cookie，参数name指定要获取的cookie的名称
function getCookie(name) {
    var start = document.cookie.indexOf(name + "="); //得到cookie字符串中的名称
    var len = start + name.length + 1; //得到从起始位置到结束cookie位置的长度
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
    //如果起始没有值且name不存在于cookie字符串中，则返回null
        return null;
    }
    if (start == -1) return null; //如果起始位置为-1也为null
    var end = document.cookie.indexOf(';', len); //获取cookie尾部位置
    if (end == -1) end = document.cookie.length; //计算cookie尾部长度
    return unescape(document.cookie.substring(len, end)); //获取cookie值
}

//设置cookie，name为名称，value为值
function setCookie(name, value) {
    var exp = new Date();
    exp.setTime(exp.getTime() + 60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function login(){
    mycode = localStorage.getItem("code");
    var data = {"empCd":mycode};
    var jsonData = JSON.stringify(data);

    $.ajax({
        url:"/login",
        type:"POST",
        data:jsonData,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async:false,

        success: function (data) {
            if (data!=null || data != "") {
                var jsDic = data["ticketCard"];
                u_name = data["empName"];
                if (jsDic) {
                    $('#wholearea tr').each(function(i){                   // 遍历 tr
                        $(this).children('td').each(function(j){  // 遍历 tr 的各个 td
                            $(this).removeAttr("onclick");
                        });
                    });
                    $(".heading").text("等待大屏抽奖");
                    $(".button1").css("display","none");
                    $(".button2").css("display","none");
                    var arr = jsDic.split(',');
                    mydatas = [];
                    mydatas = arr.concat();
                    for (v in arr){
                        let zip_id = parseInt(arr[v]);
                        for (j in nation_data)
                        {
                            let name = nation_data[j]["name"];
                            let code_id = parseInt(nation_data[j]["zip"]);
                            if (code_id == zip_id) {
                                let textId = myarr[v].substring(6);
                                document.getElementById(textId).innerHTML=name;
                            }
                        }
                    }
                    reloadSocket();
                    var jsDicWM = data["winningNumbers"];
                    if (jsDicWM) {
                        var arrwm = jsDicWM.split(',');
                        var end = arrwm[arrwm.length-1];
                        if (end == "ok") {
                            reSuccess = true;
                            arrwm.pop();
                        }
                        storageYao=[];
                        storageYao=arrwm.concat();
                        for (x in arrwm){
                            let yao_id = arrwm[x];
                            for (k in arr) {
                                let zip_id = parseInt(arr[k]);
                                if (zip_id == parseInt(yao_id)) {
                                    let id = myarr[k];
                                    document.getElementById(id).className = "pickedBG";
                                    checkWin(id.substring(6));
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    $(".button1").css("display","");
                    $(".button2").css("display","");
                }
            }
        },
        error: function (xhr) {
            // 隐藏 loading
            // 只有请求不正常（状态码不为200）才会执行
            console.log('error', xhr)
        },
        complete: function (xhr) {
            // 不管是成功还是失败都是完成，都会执行这个 complete 函数
            console.log('complete', xhr)
        }
    });
}

var reSuccess = false;

function postWM(strList){
    console.log(strList);
    mycode = localStorage.getItem("code");
    var data = {"empCd":mycode,"winningNumbers":strList};
    var jsonData = JSON.stringify(data);
    $.ajax({
        url:"/wm",
        type:"POST",
        data:jsonData,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async:false,

        success: function (data) {
            if (data!=null || data != "") {
            }
        },
        error: function (xhr) {
            // 隐藏 loading
            // 只有请求不正常（状态码不为200）才会执行
            console.log('error', xhr)
        },
        complete: function (xhr) {
            // 不管是成功还是失败都是完成，都会执行这个 complete 函数
            console.log('complete', xhr)
        }
    });
}

//登录成功连接
var stompClient = null;
function reloadSocket(){

    //<!-- Reload Bingo Card  -->
    var socket = new SockJS('/bpo-raffle-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        // setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/raffle/bingo', function (bingo) {
            if (!reSuccess) {
                showGreeting(JSON.parse(bingo.body).content);
            }
        });
        stompClient.subscribe('/raffle/restart', function (bingo) {
            showRestart(JSON.parse(bingo.body).content);
        });
    });
}

function showRestart(message){
    postWM("");
    window.location.reload();
}

var storageYao = []; //上传的数组
function showGreeting(message) {
    message = JSON.parse(message);
	console.log(message);
    let yao_id = message["zip"];

    let yaoidstr = parseInt(yao_id).toString();

    //----------------------------------------------------

    //----------------------------------------------------
    for (v in mydatas) {
        let zip_id = parseInt(mydatas[v]);

        if (zip_id == parseInt(yao_id)) {
            //上传中奖的号码
            storageYao.push(yaoidstr);
            postWM(storageYao.join(","))

            let id = myarr[v];
            document.getElementById(id).className = "pickedBG";
            checkWin(id.substring(6));

            break;
        }
    }


}
function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    console.log("Disconnected");
}

// var copy_nation = new Array()
//点击后选择完 删除一个
function colorToggle(id){   //<!-- Toggle the color-->
    $('#tc').css("display","");
    $("#selectSM").empty();
    // console.log(nation_data);
    kkId = id;
    if (no_select_citys.length == 0) {
        no_select_citys = nation_data.concat();
    }
    for (x in no_select_citys)
    {
        let name = no_select_citys[x]["name"];
        let code_id = no_select_citys[x]["zip"];
        // console.log(name);
        // console.log(code_id);
        $("#selectSM").append("<option value='"+code_id+"'>"+name+"</option>");

    }

    // document.getElementById(myarr[i]).innerHTML=x
}
var kkId = ""; //点击框框
var postNationDic = {};
function save_hidder(){
    console.log(kkId);

    //获取选中项的文本值
    var itemVal = parseInt($("#selectSM").val());
    postNationDic[kkId] = parseInt($("#selectSM").val());
    for (x in no_select_citys){
        let code_id = no_select_citys[x]["zip"];
        if (code_id==itemVal) {
            no_select_citys.splice(x,1);
            $("#selectSM option[index=x]").remove();
            console.log(code_id);
            break;
        }
    }

    console.log(Object.keys(postNationDic).length);
    console.log(postNationDic);

    let textId = kkId.substring(6);

    document.getElementById(textId).innerHTML=$("#selectSM option:selected").text();
    $('#tc').css("display","none");
    // document.getElementById('zhezhao').style.display="none";
}

function hidder(){
    $('#tc').css("display","none");
    // document.getElementById('zhezhao').style.display="none";
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    // setConnected(false);
    console.log("Disconnected");
}
var success = false;
function checkWin(strNum){
    //存储用户可能遇到的获胜选项
    var winningOption = -1;
    var setSquares = 0;

    //设置获胜编码
    var winners = new Array(31,992,15360,507904,541729,557328,1083458,2162820,4329736,8519745,8659472,16252928);

    //执行完后，产生一个24位的数字，存储用户已经单击的格子，每一位的数值代表那个格的点击状态，被点击则设为1，否则设为0。如第一格没被点击过，第二格被点击过setSquares就为10
    for(var i=0; i < 24; i++){
        var currSquare = "square"+i;
        if(document.getElementById(currSquare).className!=""){
            document.getElementById(currSquare).className = "pickedBG";
            // document.getElementById(currSquare).innerHTML="🇨🇳";
            // document.getElementById(currSquare).style.color="gold";
            setSquares = setSquares | Math.pow(2,i);
        }
     }

    //判断用户选择是否是获胜状态
    for(var i=0; i<winners.length; i++){
        if((winners[i]&setSquares) == winners[i]){
            winningOption = i;
            $('#wholearea tr').each(function(i){                   // 遍历 tr
               $(this).children('td').each(function(j){  // 遍历 tr 的各个 td
                 $(this).removeAttr("onclick");
               });
            });
            success = true;

        }
    }
    //
    if(winningOption > -1){
        for(var i=0; i < 24; i++){
            if(winners[winningOption] & Math.pow(2,i))
            {
                var currSquare = "square"+i;
                document.getElementById(currSquare).className = "bingo";
            }
        }
    }

    if (!reSuccess && success){
        reSuccess = true;
        stompClient.send("/bpo/zhongjiang", {}, JSON.stringify({'name': u_name}));
        storageYao.push("ok");
        postWM(storageYao.join(","))
        alert('✌✌✌胜利✌✌✌');
    }

}
var u_name = "";
var no_select_citys = []; //没有随机到的城市

function randomC(){
    var copy_na = nation_data.concat();
    for (x in myarr){
        let square_id = myarr[x];
        // if (x==0){
        //     postNationDic[square_id] = 666;
        //     continue;
        // }
        let temp = parseInt(Math.random() * copy_na.length);
        let zip_str = copy_na[temp].zip;
        let na_name = copy_na[temp].name;

        postNationDic[square_id] = parseInt(zip_str);
        let textId = square_id.substring(6);
        document.getElementById(textId).innerHTML=na_name;
        copy_na.splice(temp,1);

    }
    no_select_citys = [];
    no_select_citys = copy_na.concat();
    console.log(no_select_citys.length);
    console.log(Object.keys(postNationDic).length);
}

var myarr=["square0","square1","square2","square3","square4",
"square5","square6","square7","square8","square9",
"square10","square11","square12","square13","square14",
"square15","square16","square17","square18","square19",
"square20","square21","square22","square23"];

//点击提交
function generate(){
    console.log(Object.keys(postNationDic).length);
    if (Object.keys(postNationDic).length < 24) {
        alert('请选择完民族');
        return;
    }
    var strList = "";
    for (var i = 0; i < myarr.length; i++) {
    	let key = myarr[i];
    	$.each(postNationDic, function (k, v) {
    		if (k == key) {
    			strList =  strList + v.toString() + ",";
    		}
    	});
    }
    console.log(strList);
	strList = strList.substring(0,strList.length-1);
	console.log(strList);
    var data = {"empCd":mycode,"ticketCard":strList};

    var jsonData = JSON.stringify(data);
    $.ajax({
        url:"/submit",
        type:"POST",
        data:jsonData,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async:false,
        success: function (data) {
            if (data!=null || data != "") {

                var jsDic = data["ticketCard"];
                var arr = jsDic.split(',');
                mydatas = arr;
                // let jsdata = JSON.stringify(arr);
                // localStorage.setItem("data", jsdata);
                // localStorage.setItem("yaodata", JSON.stringify([]));
                // console.log(jsdata);

                $(".heading").text("等待大屏抽奖");
                $(".button1").css("display","none");
                $(".button2").css("display","none");
                // $(".numbers").removeAttr("onclick");
                $('#wholearea tr').each(function(i){                   // 遍历 tr
                   $(this).children('td').each(function(j){  // 遍历 tr 的各个 td
                     $(this).removeAttr("onclick");
                   });
                });
                // var jsonData = JSON.stringify(postNationDic);
                // localStorage.setItem("data", jsonData);
                reloadSocket();
            }
            else {
                $(".button1").css("display","");
                $(".button2").css("display","");
                $("#mobile-err span").html(data.errmsg);
                $("#mobile-err").show();

                return;
            }
        },
        error: function (xhr) {
            // 隐藏 loading
            // 只有请求不正常（状态码不为200）才会执行
        console.log('error', xhr)
      }
    });
}
var nation_data = [
    {label:"北京Beijing010",name:"北京",pinyin:"Beijing",zip:"010"},
    {label:"重庆Chongqing023",name:"重庆",pinyin:"Chongqing",zip:"023"},
    {label:"上海Shanghai021",name:"上海",pinyin:"Shanghai",zip:"021"},
    {label:"天津Tianjin022",name:"天津",pinyin:"Tianjin",zip:"022"},
    {label:"长春Changchun0431",name:"长春",pinyin:"Changchun",zip:"0431"},
    {label:"长沙Changsha0731",name:"长沙",pinyin:"Changsha",zip:"0731"},
    {label:"常州Changzhou0519",name:"常州",pinyin:"Changzhou",zip:"0519"},
    {label:"成都Chengdu028",name:"成都",pinyin:"Chengdu",zip:"028"},
    {label:"大连Dalian0411",name:"大连",pinyin:"Dalian",zip:"0411"},
    {label:"东莞Dongguan0769",name:"东莞",pinyin:"Dongguan",zip:"0769"},
    {label:"佛山Foshan0757",name:"佛山",pinyin:"Foshan",zip:"0757"},
    {label:"福州Fuzhou0591",name:"福州",pinyin:"Fuzhou",zip:"0591"},
    {label:"广州Guangzhou020",name:"广州",pinyin:"Guangzhou",zip:"020"},
    {label:"贵阳Guiyang0851",name:"贵阳",pinyin:"Guiyang",zip:"0851"},
    {label:"哈尔滨Haerbin0451",name:"哈尔滨",pinyin:"Haerbin",zip:"0451"},
    {label:"海口Haikou0898",name:"海口",pinyin:"Haikou",zip:"0898"},
    {label:"邯郸Handan0310",name:"邯郸",pinyin:"Handan",zip:"0310"},
    {label:"襄樊Xiangfan0710",name:"襄樊",pinyin:"Xiangfan",zip:"0710"},
    {label:"合肥Hefei0551",name:"合肥",pinyin:"Hefei",zip:"0551"},
    {label:"惠州Huizhou0752",name:"惠州",pinyin:"Huizhou",zip:"0752"},
    {label:"焦作Jiaozuo0391",name:"焦作",pinyin:"Jiaozuo",zip:"0391"},
    {label:"嘉兴Jiaxing0573",name:"嘉兴",pinyin:"Jiaxing",zip:"0573"},
    {label:"吉林Jilin0423",name:"吉林",pinyin:"Jilin",zip:"0423"},
    {label:"济南Jinan0531",name:"济南",pinyin:"Jinan",zip:"0531"},
    {label:"昆明Kunming0871",name:"昆明",pinyin:"Kunming",zip:"0871"},
    {label:"兰州Lanzhou0931",name:"兰州",pinyin:"Lanzhou",zip:"0931"},
    {label:"柳州Liuzhou0772",name:"柳州",pinyin:"Liuzhou",zip:"0772"},
    {label:"洛阳Luoyang0379",name:"洛阳",pinyin:"Luoyang",zip:"0379"},
    {label:"南昌Nanchang0791",name:"南昌",pinyin:"Nanchang",zip:"0791"},
    {label:"南京Nanjing025",name:"南京",pinyin:"Nanjing",zip:"025"},
    {label:"南宁Nanning0771",name:"南宁",pinyin:"Nanning",zip:"0771"},
    {label:"南通Nantong0513",name:"南通",pinyin:"Nantong",zip:"0513"},
    {label:"宁波Ningbo0574",name:"宁波",pinyin:"Ningbo",zip:"0574"},
    {label:"青岛Qingdao0532",name:"青岛",pinyin:"Qingdao",zip:"0532"},
    {label:"泉州Quanzhou0595",name:"泉州",pinyin:"Quanzhou",zip:"0595"},
    {label:"沈阳Shenyang024",name:"沈阳",pinyin:"Shenyang",zip:"024"},
    {label:"深圳Shenzhen0755",name:"深圳",pinyin:"Shenzhen",zip:"0755"},
    {label:"石家庄Shijiazhuang0311",name:"石家庄",pinyin:"Shijiazhuang",zip:"0311"},
    {label:"苏州Suzhou0512",name:"苏州",pinyin:"Suzhou",zip:"0512"},
    {label:"台州Taizhou0576",name:"台州",pinyin:"Taizhou",zip:"0576"},
    {label:"唐山Tangshan0315",name:"唐山",pinyin:"Tangshan",zip:"0315"},
    {label:"潍坊Weifang0536",name:"潍坊",pinyin:"Weifang",zip:"0536"},
    {label:"威海Weihai0631",name:"威海",pinyin:"Weihai",zip:"0631"},
    {label:"武汉Wuhan027",name:"武汉",pinyin:"Wuhan",zip:"027"},
    {label:"无锡Wuxi0510",name:"无锡",pinyin:"Wuxi",zip:"0510"},
    {label:"厦门Xiamen0592",name:"厦门",pinyin:"Xiamen",zip:"0592"},
    {label:"西安Xian029",name:"西安",pinyin:"Xian",zip:"029"},
    {label:"许昌Xuchang0374",name:"许昌",pinyin:"Xuchang",zip:"0374"},
    {label:"徐州Xuzhou0516",name:"徐州",pinyin:"Xuzhou",zip:"0516"},
    {label:"扬州Yangzhou0514",name:"扬州",pinyin:"Yangzhou",zip:"0514"},
    {label:"烟台Yantai0535",name:"烟台",pinyin:"Yantai",zip:"0535"},
    {label:"漳州Zhangzhou0596",name:"漳州",pinyin:"Zhangzhou",zip:"0596"},
    {label:"郑州Zhengzhou0371",name:"郑州",pinyin:"Zhengzhou",zip:"0371"},
    {label:"中山Zhongshan0760",name:"中山",pinyin:"Zhongshan",zip:"0760"},
    {label:"珠海Zhuhai0756",name:"珠海",pinyin:"Zhuhai",zip:"0756"},
    {label:"秦皇岛Qinhuangdao0335",name:"秦皇岛",pinyin:"Qinhuangdao",zip:"0335"},
    {label:"临沂Linyi0539",name:"临沂",pinyin:"Linyi",zip:"0539"},
    {label:"安康Ankang0915",name:"安康",pinyin:"Ankang",zip:"0915"},
    {label:"安庆Anqing0556",name:"安庆",pinyin:"Anqing",zip:"0556"},
    {label:"鞍山Anshan0412",name:"鞍山",pinyin:"Anshan",zip:"0412"},
    {label:"安阳Anyang0372",name:"安阳",pinyin:"Anyang",zip:"0372"},
    {label:"白城Baicheng0436",name:"白城",pinyin:"Baicheng",zip:"0436"},
    {label:"百色Baise0776",name:"百色",pinyin:"Baise",zip:"0776"},
    {label:"白山Baishan0439",name:"白山",pinyin:"Baishan",zip:"0439"},
    {label:"白银Baiyin0943",name:"白银",pinyin:"Baiyin",zip:"0943"},
    {label:"蚌埠Bangbu0552",name:"蚌埠",pinyin:"Bangbu",zip:"0552"},
    {label:"保定Baoding0312",name:"保定",pinyin:"Baoding",zip:"0312"},
    {label:"宝鸡Baoji0917",name:"宝鸡",pinyin:"Baoji",zip:"0917"},
    {label:"保山Baoshan0875",name:"保山",pinyin:"Baoshan",zip:"0875"},
    {label:"包头Baotou0472",name:"包头",pinyin:"Baotou",zip:"0472"},
    {label:"巴中Bazhong0827",name:"巴中",pinyin:"Bazhong",zip:"0827"},
    {label:"北海Beihai0779",name:"北海",pinyin:"Beihai",zip:"0779"},
    {label:"本溪Benxi0414",name:"本溪",pinyin:"Benxi",zip:"0414"},
    {label:"滨州Binzhou0543",name:"滨州",pinyin:"Binzhou",zip:"0543"},
    {label:"亳州Bozhou0558",name:"亳州",pinyin:"Bozhou",zip:"0558"},
    {label:"沧州Cangzhou0317",name:"沧州",pinyin:"Cangzhou",zip:"0317"},
    {label:"常德Changde0736",name:"常德",pinyin:"Changde",zip:"0736"},
    {label:"昌都Changdu0895",name:"昌都",pinyin:"Changdu",zip:"0895"},
    {label:"昌吉Changji0997",name:"昌吉",pinyin:"Changji",zip:"0997"},
    {label:"长治Changzhi0355",name:"长治",pinyin:"Changzhi",zip:"0355"},
    {label:"巢湖Chaohu0565",name:"巢湖",pinyin:"Chaohu",zip:"0565"},
    {label:"朝阳Chaoyang0421",name:"朝阳",pinyin:"Chaoyang",zip:"0421"},
    {label:"潮州Chaozhou0768",name:"潮州",pinyin:"Chaozhou",zip:"0768"},
    {label:"赤峰Chifeng0476",name:"赤峰",pinyin:"Chifeng",zip:"0476"},
    {label:"池州Chizhou0566",name:"池州",pinyin:"Chizhou",zip:"0566"},
    {label:"金华Jinhua0579",name:"金华",pinyin:"Jinhua",zip:"0579"},
    {label:"楚雄Chuxiong0879",name:"楚雄",pinyin:"Chuxiong",zip:"0879"},
    {label:"滁州Chuzhou0550",name:"滁州",pinyin:"Chuzhou",zip:"0550"},
    {label:"大理Dali0872",name:"大理",pinyin:"Dali",zip:"0872"},
    {label:"丹东Dandong0415",name:"丹东",pinyin:"Dandong",zip:"0415"}
];
